/*  This file is part of YATracker.
    YATracker is free software: you can redistribute it and/or modify it under the terms
of the GNU Lesser General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
    YATracker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
    You should have received a copy of the GNU Lesser General Public License along with
YATracker. If not, see <http://www.gnu.org/licenses/>. */

#include <stdlib.h>
#include "yatmapfile.h"


YatMapFile::YatMapFile()
{
    m_index = NULL;
    memset(&m_header, 0, sizeof(YatMapFileHeader));
}

bool YatMapFile::open(const QString &fileName)
{
    m_file.setFileName(fileName);
    if (!m_file.open(QIODevice::ReadOnly))
        return false;

    m_file.read((char*)(&m_header), sizeof(YatMapFileHeader));
    //TODO: Check file prefix

    m_index = (YatMapIndexItem*) malloc(sizeof(YatMapIndexItem) * m_header.indexSizeInItems);
    //TODO: Check for read error

    m_file.read((char*)(this->m_index), sizeof(YatMapIndexItem) * m_header.indexSizeInItems);
    //TODO: Check for read error

    return true;  //STUB
}

void YatMapFile::close()
{
    m_file.close();

    if (m_index != NULL)
    {
        free(m_index);
    }
}

bool YatMapFile::hasTile(quint32 x, quint32 y)
{
    if (m_header.tileminx > x || m_header.tilemaxx < x ||
        m_header.tileminy > y || m_header.tilemaxy < y)
        return false;
    //TODO: Check for the tile using the index
    return true;  //STUB
}

void* YatMapFile::getTile(quint32 x, quint32 y, int *pdatasize)
{
    *pdatasize = 0;
    if (m_header.tileminx > x || m_header.tilemaxx < x ||
        m_header.tileminy > y || m_header.tilemaxy < y)
        return NULL;  // Out of map range

    for (quint32 i = 0; i < m_header.indexSizeInItems; i++)
    {
        if (m_index[i].tilex == x && m_index[i].tiley == y)
        {
            void* pdata = malloc(m_index[i].dataSize);
            m_file.seek(m_header.dataOffset + m_index[i].dataOffset);
            m_file.read((char*)pdata, m_index[i].dataSize);
            //TODO: Check for read error
            *pdatasize = m_index[i].dataSize;
            return pdata;
        }
    }

    return NULL;  // Tile was not found
}
